<?
require_once("lib/php/controller/ViewController.php");
require_once("ericdingle/php/Authentication.php");
require_once("ericdingle/model/comment/CommentProvider.php");
require_once("ericdingle/model/post/PostProvider.php");
require_once("ericdingle/model/label/LabelProvider.php");
require_once("ericdingle/model/link/LinkProvider.php");

class ViewPost extends ViewController {
	public function doGet() {
		// get authentication
		$auth = Authentication::getInstance();
		
		// get params
		$postID = $_GET["postID"];
		
		// get labels
		$labelProvider = LabelProvider::getInstance();
		$labels = $labelProvider->read();
		
		// get links
		$linkProvider = LinkProvider::getInstance();
		$links = $linkProvider->read();
		
		// get posts and comments
		$postProvider = PostProvider::getInstance();
		$post = $postProvider->readByPostID($postID);
		
		$commentProvider = CommentProvider::getInstance();
		$comments = $commentProvider->readByPostID($postID);
		
		// load views
		require_once("ericdingle/php/Tabs.php");
		$this->loadView("ericdingle/view/header.php", array(
			"isLoggedIn" => $auth->isLoggedIn(),
			"tabID" => TabID::BLOG,
			"tabs" => $tabs,
			"css_files" => array("css/viewPost.css", "css/blogNav.css", "css/post.css"),
			"js_files" => array("js/viewPost.js")
		));
		$this->loadView("ericdingle/view/viewPost.php", array(
			"isLoggedIn" => $auth->isLoggedIn(),
			"labels" => $labels,
			"links" => $links,
			"post" => $post,
			"comments" => $comments
		));
		$this->loadView("ericdingle/view/footer.php");
	}
	
	public function doPost() {
		// get authentication
		$auth = Authentication::getInstance();
		
		if ($_POST["deleteComment"] && $auth->isLoggedIn()) {
			$commentID = $_POST["commentID"];
			$commentProvider = CommentProvider::getInstance();
			$commentProvider->deleteByCommentID($commentID);
		} else if ($_POST["postComment"] && $_POST["jsValid"] == "true") {
			$postID = $_POST["postID"];
			$name = stripslashes($_POST["commentName"]);
			$name = htmlentities($name);
			
			$content = stripslashes($_POST["commentContent"]);
			$content = htmlentities($content);
			$content = str_replace("\n", "<br/>", $content);
			
			$commentProvider = CommentProvider::getInstance();
			$comment = new CommentEntity(
				null,
				$postID,
				$name,
				new PostDate(),
				$content);
			$commentProvider->create($comment);
			
			mail("eric.dingle@gmail.com", "New comment on ericdingle.com",
				"http://www.ericdingle.com/viewPost?postID=$postID",
				"From: viewPost@ericdingle.com\r\n" .
				"X-Mailer: PHP/" . phpversion());
		}
		
		$this->doGet();
	}
}
?>
